package com.nd.android.musicboxlibrary.util.fastDateUtil;

import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.util.FastDateFormat;

import java.util.Calendar;

/**
 * <p>
 * Inner class to output a padded number.
 * </p>
 */
public class PaddedNumberField implements NumberRule {
    private final int mField;

    private final int mSize;

    /**
     * Constructs an instance of <code>PaddedNumberField</code>.
     * 
     * @param field
     *            the field
     * @param size
     *            size of the output field
     */
    public PaddedNumberField(int field, int size) {
        if (size < MagicNumber.n3) {
            // Should use UnpaddedNumberField or TwoDigitNumberField.
            throw new IllegalArgumentException();
        }
        mField = field;
        mSize = size;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int estimateLength() {
        return MagicNumber.n4;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void appendTo(StringBuffer buffer, Calendar calendar) {
        appendTo(buffer, calendar.get(mField));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void appendTo(StringBuffer buffer, int value) {
        if (value < MagicNumber.n100) {
            for (int i = mSize; --i >= 2;) {
                buffer.append('0');
            }
            buffer.append((char) (value / MagicNumber.n10 + '0'));
            buffer.append((char) (value % MagicNumber.n10 + '0'));
        } else {
            int digits;
            if (value < MagicNumber.n1000) {
                digits = MagicNumber.n3;
            } else {
                FastDateFormat.isTrue(value > -1, "Negative values should not be possible", value);
                digits = Integer.toString(value).length();
            }
            for (int i = mSize; --i >= digits;) {
                buffer.append('0');
            }
            buffer.append(Integer.toString(value));
        }
    }
}
